package com.base.monitor.module.biz.handler;

import com.alibaba.fastjson.JSONObject;
import com.base.monitor.framework.util.ConcurrentUtil;
import com.base.monitor.framework.util.DiskUtils;
import com.base.monitor.model.model.biz.collect.entity.CollectData;
import com.base.monitor.module.biz.mq.MonitorQueueProducer;
import com.base.monitor.module.biz.properties.ParamProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 这个handler是用来推送采集数据的
 */
@Component
@Slf4j
@EnableConfigurationProperties(ParamProperties.class)
public class HandleCollectDataHandler implements InitializingBean {

    private final BlockingQueue<CollectData> HandleDataQueue = new LinkedBlockingQueue<>(5000);

    @Autowired
    private MonitorQueueProducer monitorQueueProducer;

    @Value("${collect.file.name}")
    private String fileName;

    @Override
    public void afterPropertiesSet() throws Exception {
        HandleTask handleTask = new HandleTask();
        new Thread(handleTask).start();
    }

    /**
     * 添加新增任务
     * @param baseCollect 新增的数据
     */
    public void addTask(CollectData baseCollect) {
        try {
            HandleDataQueue.put(baseCollect);
        } catch (InterruptedException e) {
            log.error("添加新增任务时发生异常", e);
        }
    }

    private class HandleTask implements Runnable {
        @Override
        public void run() {
            log.info("开始推送采集数据");
            while (true) {
                try {
                    CollectData collectData = HandleDataQueue.take();
                    log.info("本次读取的采集数据是{}", collectData);

                    // 1.将数据写到文件中
                    writeCollectToLocalFile(collectData);

                    // 2.推送
                    monitorQueueProducer.sendTextMessage(JSONObject.toJSONString(collectData));
                    log.info("本次推送采集数据成功");
                } catch (Exception e) {
                    log.error("本次推送采集数据失败，原因是：{}", e.getMessage());
                }
            }
        }
    }

    /**
     * 将记录写到文件中去
     * @param collect 记录信息
     */
    private void writeCollectToLocalFile(CollectData collect) {
        Map<String, Object> map = new HashMap<>();
        map.put("indicatorId", collect.getIndicatorId());
        map.put("collectTime", ConcurrentUtil.format(new Date()));
        map.put("value", collect.getValue());
        DiskUtils.writeTxt(fileName, JSONObject.toJSONString(map) + "\r\n");
    }
}
